from collections import defaultdict


class Solution:
    def calcEquation(self, equations, values, queries):
        # 构建初始比值图
        graph = defaultdict(dict)
        for (u, v), val in zip(equations, values):
            graph[u][v] = val
            graph[v][u] = 1 / val

        # 动态规划填充所有可能的比值
        variables = set(graph.keys())
        dp = defaultdict(dict)

        # 初始化直接关系
        for u in variables:
            for v in graph[u]:
                dp[u][v] = graph[u][v]

        # 通过中间变量更新关系
        for k in variables:
            for i in variables:
                for j in variables:
                    if k in dp[i] and j in dp[k] and j not in dp[i]:
                        dp[i][j] = dp[i][k] * dp[k][j]

        # 处理查询
        results = []
        for u, v in queries:
            if u in dp and v in dp[u]:
                results.append(dp[u][v])
            elif u == v and u in variables:
                results.append(1.0)
            else:
                results.append(-1.0)
        return results
